'use client'

import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  Button,
  Box,
  Text,
  Heading,
  VStack,
  HStack,
  Divider,
  Image,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  useColorModeValue
} from '@chakra-ui/react'

export interface Attachment {
  id: string;
  name: string;
  type: 'chapter' | 'character' | 'scene' | 'note' | 'image' | string;
  content: string | any;
  createdAt: string;
  updatedAt: string;
}

interface AttachmentPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  attachment: Attachment | null;
  onEdit?: (attachment: Attachment) => void;
}

export const AttachmentPreviewModal = ({
  isOpen,
  onClose,
  attachment,
  onEdit
}: AttachmentPreviewModalProps) => {
  if (!attachment) return null;
  
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  
  // 根据附件类型渲染不同的预览内容
  const renderContent = () => {
    try {
      // 尝试解析内容为JSON
      const parsedContent = typeof attachment.content === 'string' 
        ? JSON.parse(attachment.content) 
        : attachment.content;
        
      switch (attachment.type) {
        case 'chapter':
          return (
            <Box>
              <Heading size="lg" mb={4}>{parsedContent.title || '未命名章节'}</Heading>
              <Text whiteSpace="pre-line">{parsedContent.content || '（无内容）'}</Text>
            </Box>
          );
          
        case 'character':
          return (
            <VStack align="stretch" spacing={4}>
              <HStack>
                {parsedContent.avatar && (
                  <Image 
                    src={parsedContent.avatar} 
                    alt={parsedContent.name} 
                    boxSize="100px"
                    borderRadius="full"
                    fallback={<Box boxSize="100px" bg="gray.200" borderRadius="full" />}
                  />
                )}
                <Box>
                  <Heading size="lg">{parsedContent.name || '未命名角色'}</Heading>
                  {parsedContent.age && parsedContent.gender && (
                    <Text color="gray.500">{parsedContent.age} 岁, {parsedContent.gender}</Text>
                  )}
                </Box>
              </HStack>
              
              <Divider />
              
              <Tabs variant="enclosed">
                <TabList>
                  <Tab>描述</Tab>
                  <Tab>背景</Tab>
                  <Tab>特征</Tab>
                </TabList>
                <TabPanels>
                  <TabPanel>
                    <Text>{parsedContent.description || '（无描述）'}</Text>
                  </TabPanel>
                  <TabPanel>
                    <Text whiteSpace="pre-line">{parsedContent.background || '（无背景信息）'}</Text>
                  </TabPanel>
                  <TabPanel>
                    {parsedContent.traits && parsedContent.traits.length > 0 ? (
                      <VStack align="stretch">
                        {parsedContent.traits.map((trait: any, index: number) => (
                          <HStack key={index}>
                            <Text fontWeight="bold">{trait.name}:</Text>
                            <Text>{trait.value}</Text>
                          </HStack>
                        ))}
                      </VStack>
                    ) : (
                      <Text>（未定义特征）</Text>
                    )}
                  </TabPanel>
                </TabPanels>
              </Tabs>
            </VStack>
          );
          
        case 'scene':
          return (
            <Box>
              <Heading size="lg" mb={4}>{parsedContent.name || '未命名场景'}</Heading>
              <Text fontSize="sm" color="gray.500" mb={4}>
                {parsedContent.location && `位置: ${parsedContent.location}`}
                {parsedContent.time && ` • 时间: ${parsedContent.time}`}
              </Text>
              <Text whiteSpace="pre-line">{parsedContent.description || '（无描述）'}</Text>
            </Box>
          );
        
        case 'image':
          return (
            <Box textAlign="center">
              <Image 
                src={parsedContent.url || attachment.content} 
                alt={attachment.name}
                maxH="500px"
                mx="auto"
                fallback={<Box h="300px" bg="gray.200" display="flex" alignItems="center" justifyContent="center">
                  <Text>图像无法加载</Text>
                </Box>}
              />
              {parsedContent.caption && (
                <Text mt={2} fontStyle="italic" color="gray.600">
                  {parsedContent.caption}
                </Text>
              )}
            </Box>
          );
          
        default:
          if (typeof attachment.content === 'string') {
            return <Text whiteSpace="pre-line">{attachment.content}</Text>;
          }
          return <Text>未知内容类型</Text>;
      }
    } catch (error) {
      console.error('解析附件内容时出错:', error);
      return <Text>无法显示内容。格式可能无效。</Text>;
    }
  };
  
  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl" scrollBehavior="inside">
      <ModalOverlay />
      <ModalContent maxW="800px">
        <ModalHeader>
          {attachment.name}
          <Text fontSize="sm" color="gray.500" mt={1}>
            {attachment.type.charAt(0).toUpperCase() + attachment.type.slice(1)}
          </Text>
        </ModalHeader>
        <ModalCloseButton />
        
        <ModalBody>
          <Box 
            p={4} 
            border="1px" 
            borderColor={borderColor} 
            borderRadius="md"
            bg={bgColor}
          >
            {renderContent()}
          </Box>
        </ModalBody>
        
        <ModalFooter>
          {onEdit && (
            <Button 
              colorScheme="blue" 
              mr={3} 
              onClick={() => onEdit(attachment)}
            >
              编辑
            </Button>
          )}
          <Button variant="ghost" onClick={onClose}>关闭</Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  )
}
